/**
 * Created by hxpeng on 2017/4/18.
 */
(function () {
    'use strict';

    angular.module('App.pages.dynamic')
        .controller('DynamicCreateCtrl', DynamicCreateCtrl);

    function DynamicCreateCtrl($scope,$state,AppUtils,DynamicModel,$location,$http,Global,LoginAccountAuth) {
        $scope.$on('$ionicView.enter', function(){
            var currentPath = $location.url();
            if(currentPath.indexOf("#") != -1){
                currentPath = currentPath.split('#')[0];
            }
            currentPath = Global.path.wechat_path + currentPath;
            $http.post(Global.path.server_sdk_auth_path,{"url":currentPath})
                .success(function(data){
                    wx.config({
                        debug: false,
                        appId: data.appId,
                        timestamp: data.timestamp,
                        nonceStr: data.noncestr,
                        signature: data.signature,
                        jsApiList: ['chooseImage','previewImage','uploadImage']
                    });
                    wx.error(function(res){
                        console.log(res);
                    });
                })
                .error(function(data,header,config,status){
                    AppUtils.showAlert("请求微信sdk校验异常");
                });
        });

        var vm = this;
        vm.loginAccount = {};
        vm.dynamic = {};
        vm.dynamic.content = '4月19日，习近平总书记来到广西壮族自治区考察调研。此前一天，外交部宣布了“一带一路”国际合作高峰论坛于5月在北京举行的消息。广西是“一带一路”交汇对接的重要门户，考察首站又定在汉代海上丝绸之路早期始发港——北海，其中深意不言自明。北海市位于广西北部湾畔，是国家历史文化名城。这里面向东南亚，背靠大西南，是西南出海大通道的重要出海口。“向海经济”“向海之路”，是习近平考察调研中反复提及的词汇。2000多年前，张骞出使西域，打通陆上丝绸之路。当时的合浦，就已经开辟通往印度、斯里兰卡的航线，成为走向东南亚、南亚的古代海上丝绸之路的重要始发港。';
        vm.imgIndex = 0;//imgUrl中保存的图片唯一标识符
        vm.imgUrl = [];//页面预览图片数组
        vm.postImgArray = [];//提交后台图片serverId数组
        $scope.localIds = "";
        vm.studentList = [];//家长绑定的孩子数字
        vm.chooseStudentList = [];//可看见动态的孩子班级
        vm.chooseStudentListTemp = [];


        LoginAccountAuth.getAccount().then(function(data){
            vm.loginAccount = data;
            angular.forEach(data.studentVoList,function(obj){
                if(!AppUtils.isUndefinedOrNull(obj.classId)){
                    vm.studentList.push(obj);
                }
            })
        })


        $scope.chooseImg = function(){
            wx.chooseImage({
                count: 9,
                sizeType: ['original', 'compressed'],
                sourceType: ['album', 'camera'],
                success: function (res) {
                    var localIds = res.localIds;
                    syncPutImg(localIds);
                    AppUtils.loading();
                }
            });
        }

        //同步上传图片
        var syncPutImg = function(localIds){
            var img = localIds.pop();
            wx.uploadImage({
                localId: img,
                isShowProgressTips: 0,
                success: function (res) {
                    var serverId = res.serverId; // 返回图片的服务器端ID
                    var obj = {};
                    obj.imgIndex = vm.imgIndex;
                    obj.url = img;
                    obj.serverId = serverId;
                    $scope.$apply(function(){
                        vm.imgUrl.push(obj);
                    });
                    vm.imgIndex++;
                    if(localIds.length > 0){
                        syncPutImg(localIds);
                    }else{
                        //$scope.uploadImg();//选择完成后上传图片
                        AppUtils.loadfinish();
                    }
                }
            });
        };

        //大图片预览
        $scope.previewImg = function(url){
            var imgArray = [];
            angular.forEach(vm.imgUrl, function(obj, index) {
                imgArray.push(obj.url);
            });
            wx.previewImage({
                current: url,
                urls: imgArray
            });
        }

        //删除选择的图片
        $scope.removePicture = function(url,imgIndex){
            var urlIndex = null;
            angular.forEach(vm.imgUrl, function(obj, index) {
                if (obj.url === url && obj.imgIndex === imgIndex) {
                    urlIndex = index;
                }
            });
            $scope.$apply(function(){
                vm.imgUrl.splice(urlIndex, 1);
            });
        }

        //页面初始化绑定事件
        $("#choose-child-btn,.entrust-create-screen").on("click",function(){
            $(".container").toggleClass('toggled');
        })
        $(".entrust-create-screen").on("click",".card-facebook",function(e){
            $(this).toggleClass('toggled');
            e.stopPropagation();
        })
        $scope.removeStudent = function(index){
            vm.chooseStudentList.splice(index, 1);
        }


        $("#choose-student-btn").on("click",function(e){
            var keepGoing = true;
            var studentList = $(".entrust-create-screen").find(".card-facebook.toggled");
            studentList.each(function(){
                var id = $(this).attr("data-studentId");
                angular.forEach(vm.chooseStudentListTemp,function(data){
                    if(data.id === id){
                        keepGoing = false;
                        return;
                    }
                })
                if(keepGoing){
                    var obj = {};
                    obj.studentId = id;
                    obj.classId = $(this).attr("data-classId");
                    obj.studentName = $(this).attr("data-studentName");
                    obj.studentAvatarPath = $(this).attr("data-studentAvatarPath");
                    vm.chooseStudentListTemp.push(obj);
                }
                $(this).removeClass("toggled");
            })
            $scope.$apply(function () {
                var obj = [];
                var addToArray=true;
                angular.forEach(vm.chooseStudentListTemp,function(a){
                    angular.forEach(vm.chooseStudentList,function(b){
                        if(b.studentId === a.studentId){
                            addToArray=false;
                            return;
                        }
                    })
                    if(addToArray){
                        vm.chooseStudentList.push(a);
                    }
                    addToArray=true;
                })
                vm.chooseStudentListTemp = [];
            });
        })


        //取动态正文和图文 填充进div，保存div的html值
        $scope.prepareDynamic = function(){
            vm.dynamic.thumbnail = "";
            var resultHtml = angular.element("#resultHtml");
            resultHtml.append("<p>"+vm.dynamic.content+"</p>");

            if(!AppUtils.isUndefinedOrNull(vm.imgUrl)){
                angular.forEach(vm.imgUrl, function(obj, index) {
                    if (!AppUtils.isUndefinedOrNull(obj.serverId)) {
                        vm.postImgArray.push(obj.serverId);
                    }
                });
                DynamicModel.submitUploadImg({serverIds: JSON.stringify(vm.postImgArray)}).$promise.then(function(response){
                    if(response.stat == 'success'){
                        //后台下载图片成功返回的文件集合
                        var fileList = response.fileList;
                        var imgBoxList = angular.element(".img-box");
                        var keepGoing;
                        var thumbnailLen = 3;
                        angular.forEach(fileList,function(obj){
                            keepGoing = true;
                            if(thumbnailLen > 0){
                                vm.dynamic.thumbnail += obj.thumbnail + ";";
                            }
                            angular.forEach(imgBoxList,function(box){
                                if(keepGoing){
                                    var img = angular.element(box).find("img")[0];
                                    if(!AppUtils.isUndefinedOrNull(img) && img.attributes['name'].value == obj.mediaId){
                                        var textarea = angular.element(box).find("textarea")[0];
                                        resultHtml.append("<div>");
                                        resultHtml.append("<img src='"+obj.filePath+"' style='width: 100%;'>");
                                        resultHtml.append("<br/>" + textarea.value);
                                        resultHtml.append("<p style='margin: 0px;'>&nbsp;</p>");
                                        resultHtml.append("</div>");
                                        keepGoing = false;
                                    }
                                }
                            })
                            thumbnailLen--;
                        })
                        $scope.commit();
                    }else if(response.stat == 'err'){
                        AppUtils.showAlert("图片上传失败失败:" + response.msg);
                        return false;
                    }
                });
            }else{
                $scope.commit();
            }
            console.log(resultHtml.html());
        }


        $scope.commit = function(){
            var obj = {};
            var classIds = [];

            if(vm.loginAccount.memberType === '1'){
                classIds.push(vm.loginAccount.classId)
            }else if(vm.loginAccount.memberType === '2'){
                angular.forEach(vm.chooseStudentList,function(data){
                    classIds.push(data.classId);
                })
            }

            if(classIds.length < 1){
                AppUtils.showTipsTop("请选择班级");
                return;
            }

            obj.classIds = _.clone(classIds);
            obj.title = vm.dynamic.title;
            obj.content = angular.element("#resultHtml").html();
            vm.dynamic.thumbnail = vm.dynamic.thumbnail.substring(0, vm.dynamic.thumbnail.length - 1)
            obj.thumbnail = vm.dynamic.thumbnail;
            DynamicModel.saveDynamic(obj).$promise.then(function(response){
                if(response.stat == 'success'){
                    $state.go("dynamic.index");
                }else{
                    AppUtils.showAlert("发布动态失败：" + response.msg + ",稍后再试试吧！");
                }
            })
        }


    }

})();
